package com.example.sunran.service.impl;

import com.example.sunran.domain.PhoneInfo;
import com.example.sunran.service.PhoneRecognizeService;

import java.io.*;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @program: 小班课1-手机号码识别
 * @description: 手机号码识别实现类
 * @author: SunRan
 * @create: 2018-11-11 11:58
 **/
public class PhoneRecognizeServiceImpl implements PhoneRecognizeService {



    @Override
    public PhoneInfo onCall(String phone) {
        String phonePrefix = phone.substring(0, 7);
        return searchPhoneInfo(phonePrefix);
    }


    public PhoneInfo searchPhoneInfo(String prefix) {

        FileInputStream fis = null;
        PhoneInfo phoneInfo = new PhoneInfo();
        AtomicBoolean find = new AtomicBoolean(false);
        try {
            fis = new FileInputStream("./phone.data.txt");
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);

            br.lines().forEach(line->{
                String[] info = line.split("\t");

                if (info[0].equals(prefix)) {
                    phoneInfo.setPhone(info[0]);
                    phoneInfo.setProvince(info[1]);
                    phoneInfo.setCity(info[2]);
                    phoneInfo.setOperator(info[3]);
                    phoneInfo.setCityCode(info[4]);
                    phoneInfo.setPostCode(info[5]);
                    find.set(true);
                }
            });

            if (find.get()) {
                return phoneInfo;
            }else{
                return null;
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }



}
